<template>
  <div id="files">
    <!--搜索-->
    <div class="search-content">
      <div>
        <el-input v-model="fileInfo" placeholder="请输入文件说明查询" prefix-icon="el-icon-search" clearable @change="inquiryList" />
        <el-select v-model="fileType" clearable placeholder="请选择文件类型"  @change="inquiryList" >
          <el-option
            v-for="item in fileTypeList"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
        <el-date-picker
          v-model="dateTimeRange"
          type="datetimerange"
          range-separator="至"
          clearable
          value-format="yyyy-MM-dd HH-mm-ss"
          @change="inquiryList"
          :picker-options="pickerOptions"
          start-placeholder="开始日期"
          end-placeholder="结束日期">
        </el-date-picker>
        <el-button type="primary" icon="el-icon-search" @click="inquiryList">查询</el-button>
      </div>
      <div class="search-apply">
        <el-button type="warning" icon="el-icon-edit" @click="addUpload">上传</el-button>
      </div>
    </div>
    <!--操作列表-->
    <div class="table">
      <el-table fit :data="tableData" style="width: 100%">
        <el-table-column label="路径" prop="path"  align="center">
          <template slot-scope="scope">
           <div @click="copyPath(scope.row.path)">
             <span v-if="scope.row.path.length<20">{{scope.row.path}}</span>
             <el-tooltip :content="scope.row.path" placement="top">
               <span>{{scope.row.path.substring(0,19)+"..."}}</span>
             </el-tooltip>
           </div>
          </template>
        </el-table-column>
        <el-table-column label="文件说明" prop="info"  align="center"  />
        <el-table-column label="文件类型" prop="type" align="center">
          <template slot-scope="scope">
            <el-tag size="small"  type="success" v-if="scope.row.type==='image'">图片</el-tag>
            <el-tag size="small"  type="info" v-if="scope.row.type==='video'">视频</el-tag>
            <el-tag size="small"  type="warning" v-if="scope.row.type==='file'">其他</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="上传时间" prop="createDate" width="170"  align="center" />
        <el-table-column label="操作"  width="280" align="center">
          <template slot-scope="scope">
            <el-button size="mini" type="primary" @click="dealwithView(scope.$index, scope.row)" v-if="scope.row.type!=='file'">查看</el-button>
            <el-button size="mini" type="success" @click="dealwithDownload(scope.$index, scope.row)">下载</el-button>
            <el-button size="mini" type="danger" @click="dealwithDelete(scope.$index, scope.row)" :disabled="!scope.row.isDelete">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!--分页-->
      <div class="pagination">
        <el-pagination
          :current-page.sync="currentPage"
          :page-sizes="[10,20,30,40,50]"
          layout="total,sizes, prev, pager, next"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
    <!--查看-->
    <el-dialog id="view-dialog" title="文件内容" :visible.sync="viewDialogVisible" destroy-on-close>
      <div>
        <img :src="viewData.httpPath" alt="图片有误" v-if="viewData.type==='image'" width="500" />
        <video :src="viewData.httpPath" controls="controls"  width="500" v-if="viewData.type==='video'" > </video>
      </div>
    </el-dialog>
    <!--上传蒙层-->
    <el-dialog id="add-dialog" title="文件上传" :visible.sync="addDialogVisible">
      <el-form label-position="right" label-width="38%"  :model="add"  :rules="addRules" ref="addRuleForm">
        <el-form-item label="文件类型：">
          <el-select v-model="add.type" clearable placeholder="请选择文件类型" @change="changeTips"  class="public" >
            <el-option
              v-for="item in addFileTypeList"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="上传文件：">
          <el-upload
            action=''
            ref="upload"
            :limit="1"
            name="file"
            :accept="formatFile"
            :on-exceed="handleExceed"
            :on-remove="handleRemove"
            :before-remove="beforeRemove"
            :auto-upload="false"
            :on-change="getFiles"
            :file-list="fileList">
            <el-button size="small" type="warning">选择文件</el-button>
            <span class="uploadTips">{{uploadTip}}</span>
          </el-upload>
          <el-progress :percentage="progress" color="lightgreen" v-if="progress!==0"></el-progress>
        </el-form-item>
        <el-form-item label="文件说明：" prop="info">
          <el-input v-model="add.info" type="textarea" :rows="3"  placeholder="请输入上传的文件说明" class="public" clearable />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button id="add-btn" type="primary" @click="addSubmit('addRuleForm')">上 传</el-button>
      </span>
    </el-dialog>
    <!--删除-->
    <el-dialog :visible.sync="delDialogVisible" width="300px" center id="del-dialog" top="20%">
      <span class="delTips">您确定要删除吗？</span>
      <span slot="footer" class="dialog-footer">
          <el-button @click="delDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="delKeys">确 定</el-button>
        </span>
    </el-dialog>
  </div>
</template>

<script>
  import {Message,Loading} from 'element-ui';
  import request from "../../utils/request";
  import axios from 'axios'
  import {baseUrl} from '../../settings'
  export default {
    name: "filelist",
    data(){
      var checkPublic = (rule, value, callback) => {
        if (!value) {
          return callback(new Error('文件说明不能为空'));
        }else {
          callback();
        }
      };
      return{
        // 查询
        fileInfo:'',
        fileType:null,
        fileTypeList:[
          {
            value:0,
            label:"图片"
          },
          {
            value:1,
            label:"视频"
          },
          {
            value:2,
            label:"其他"
          },
        ],
        dateTimeRange:[],
          pickerOptions: {
              shortcuts: [
                  {
                      text: '今天',
                      onClick(picker) {
                          const end = new Date();
                          const start = new Date(end.getFullYear(), end.getMonth(), end.getDate(), 0, 0, 0);
                          picker.$emit('pick', [start, end]);
                      }
                  },
                  {
                      text: '昨天',
                      onClick(picker) {
                          const date = new Date();
                          date.setTime(date.getTime() - 3600 * 1000 * 24);
                          let start = new Date(date.getFullYear(), date.getMonth(), date.getDate(), 0, 0, 0);
                          let end = new Date(new Date().getFullYear(), new Date().getMonth(), date.getDate(), 23, 59, 59);
                          picker.$emit('pick', [start, end]);
                      }
                  },
                  {
                      text: '前天',
                      onClick(picker) {
                          const date = new Date();
                          date.setTime(date.getTime() - 3600 * 1000 * 24* 2);
                          let start = new Date(date.getFullYear(), date.getMonth(), date.getDate(), 0, 0, 0);
                          let end = new Date(new Date().getFullYear(), new Date().getMonth(), date.getDate(), 23, 59, 59);
                          picker.$emit('pick', [start, end]);
                      }
                  },
                  {
                      text: '本月',
                      onClick(picker) {
                          const end = new Date();
                          const start = new Date(end.getFullYear(), end.getMonth(), 1, 0, 0, 0);
                          picker.$emit('pick', [start, end]);
                      }
                  },
                  {
                      text: '上月',
                      onClick(picker) {
                          const date = new Date();
                          date.setTime(date.getTime() - 3600 * 1000 * 24 * 30);
                          let start = new Date(date.getFullYear(), date.getMonth(), 1, 0, 0, 0);
                          let end = new Date(new Date().getFullYear(), new Date().getMonth(), 1, 23, 59, 59);
                          end.setTime(end.getTime() - 3600 * 24 * 1000);
                          picker.$emit('pick', [start, end]);
                      }
                  },
                  {
                      text: '最近一周',
                      onClick(picker) {
                          const end = new Date();
                          const start = new Date();
                          start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
                          picker.$emit('pick', [start, end]);
                      }
                  },
                  {
                      text: '最近一个月',
                      onClick(picker) {
                          const end = new Date();
                          const start = new Date();
                          start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
                          picker.$emit('pick', [start, end]);
                      }
                  },
                  {
                      text: '最近三个月',
                      onClick(picker) {
                          const end = new Date();
                          const start = new Date();
                          start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
                          picker.$emit('pick', [start, end]);
                      }
                  }
              ]
          },
        // 列表数据
        tableData:[],
        //新增
        addDialogVisible:false,
        add:{
          type:'image',
          info:""
        },
        progress:0,
        files:[],
        addFileTypeList:[
          {
            value:'image',
            label:"图片"
          },
          {
            value:'video',
            label:"视频"
          },
          {
            value:'file',
            label:"其他"
          },
        ],
        fileList:[],
        formatFile:".bmp,.jpg,.jpeg,.png,.gif",
        uploadTip:"格式只能为.bmp .jpg .jpeg .png .gif",
        addRules:{
          info:[{validator: checkPublic, trigger: 'blur' }]
        },
        //查看
        viewDialogVisible:false,
        viewData:{},
        // 删除
        delId:null,
        delDialogVisible:false,
        //分页
        currentPage: 1,
        pageSize:10,
        total: 0
      }
    },
    mounted() {
      this.inquiryList();
    },
    methods:{
      isNotNull(value){
        return value !== null && value !== undefined && value !== "";
      },
      //查询列表
      inquiryList(){
        let that=this;
        that.tableData=[];
        let data={
          pageNumber:that.currentPage,
          pageSize:that.pageSize,
          filters:[]
        };
        if(this.isNotNull(that.fileInfo)){  //文件说明
          data.filters.push({
            property:"info",
            value:that.fileInfo,
            operator: "like"
          })
        }
        if(this.isNotNull(that.fileType)){ //文件类型
          data.filters.push({
            property:"type",
            value:that.fileType,
            operator: "eq"
          })
        }
        if(this.isNotNull(that.dateTimeRange)){ //上传时间
          data.filters.push({
            property:"create_date",
            value:that.dateTimeRange[0],
            operator: "ge"
          });
          data.filters.push({
            property:"create_date",
            value:that.dateTimeRange[1],
            operator: "le"
          })
        }
        request({
          method: 'post',
          url: 'admin/file/list',
          headers:{
            'Content-Type': 'application/json;charset=UTF-8'
          },
          data:data
        }).then(function (res) {
          if(res.code===200){
            that.total=res.data.total;
            let arr=res.data.records;
            if(arr.length===0){
              that.tableData=[];
            }else{
              that.tableData=arr
            }
          }
        }).catch(function (error) {
          console.log(error);
        });
      },
      copyPath(value){
        let oInput = document.createElement('input');
        oInput.value = value;
        document.body.appendChild(oInput);
        oInput.select(); // 选择对象;
        document.execCommand("Copy"); // 执行浏览器复制命令
        this.$message({
          message: '复制成功',
          type: 'success'
        });
        oInput.remove();
      },
      //新增
      format(percentage) {
        return percentage === 100 ? '正在保存中...' : `${percentage}%`;
      },
      addUpload(){
        this.addDialogVisible=true;
      },
      changeTips(value){
        if(value==='image'){
          this.uploadTip="格式只能为.bmp .jpg .jpeg .png .gif";
          this.formatFile=".bmp,.jpg,.jpeg,.png,.gif";
        }else if(value==='video'){
          this.uploadTip="格式只能为.avi .mov .rmvb .rm .mp4 .3gp";
          this.formatFile=".avi,.mov,.rmvb,.rm,.mp4,.3gp";
        }else{
          this.uploadTip="";
          this.formatFile=null;
        }
      },
      handleRemove(files, fileList) {
        console.log(file, fileList);
      },
      //文件超出个数限制
      handleExceed(files, fileList) {
        Message.warning('一次只能上传一个文件');
      },
      //移除前提示
      beforeRemove(file, fileList) {
        return this.$confirm(`确定移除 ${ file.name }？`);
      },
      getFiles(file){
        this.files = file.raw;
      },
      addSubmit(formName){
        this.$refs[formName].validate((valid) => {
          if (valid) {
            let that=this;
            if(!that.files || that.files.length===0){
              Message.warning('请选择需要上传的文件');
              return false;
            }
            // 创建表单对象
            let form = new FormData();
            // 后端接受参数 ，可以接受多个参数
            form.append("file",that.files);
            form.append("type",that.add.type);
            form.append("info",that.add.info);
            var config = {
              onUploadProgress: progressEvent => {
                var complete = (progressEvent.loaded / progressEvent.total * 100 | 0);
                that.progress = complete
              },
              withCredentials:true
            };
            axios.post(`${baseUrl}admin/file/upload`,
              form, config).then((res) => {
              if (res.data.code === 200) {
                that.addDialogVisible = false;
                that.inquiryList();
                Message.success("文件上传成功");
                that.$refs.upload.clearFiles();
                that.$refs['addRuleForm'].resetFields();
              }
            }).catch(function (error) {
              console.log(error);
            });
          } else {
            return false;
          }
        });
      },
      //查看
      dealwithView(index, row){
        this.viewDialogVisible=true;
        this.viewData=row;
        console.log(row)
      },
      //下载
      dealwithDownload(index,row){
        let downloadUrl=row.httpPath;
        window.open(downloadUrl)
      },
      //删除
      dealwithDelete(index, row){
        this.delDialogVisible=true;
        this.delId=row.id;
      },
      delKeys(){
        let that=this;
        that.delDialogVisible=false;
        request({
          method: 'post',
          url: 'admin/file/delete/'+that.delId,
        }).then(function (res) {
          if(res.code===200){
            Message.success("删除成功");
            that.delId=null;
            that.inquiryList();
          }
        }).catch(function (error) {
          console.log(error);
        });
      },
      // 改变每页显示的数量
      handleSizeChange(val) {
        this.pageSize=val;
        this.inquiryList();
      },
      //改变当前页
      handleCurrentChange(val) {
        this.currentPage=val;
        this.inquiryList();
      }
    }
  }
</script>

<style src="../../assets/css/fileManagement/filelist.css">

</style>
